# -- coding:UTF-8 --
import cv2
import numpy as np

pre_corner_point = [(0, 0), (0, 0), (0, 0), (0, 0)]
pre_max_length = 0
count = False


def extract_focus(img, scale):
    source_img = img.copy()
    img = cv2.GaussianBlur(img, (5, 5), 0, 0)

    # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    # img = cv2.dilate(img, kernel)
    canny = cv2.Canny(img, 40, 150)
    # cv2.imshow("canny", canny)
    k = np.ones((5, 5), np.uint8)
    canny = cv2.morphologyEx(canny, cv2.MORPH_CLOSE, k)
    cv2.imshow("canny", canny)

    contours, hierarchy = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    contours = sorted(contours, key=cv2.contourArea, reverse=True)[:1]
    if len(contours)==0:
        return 0,False
    max_length=abs(cv2.arcLength(contours[0], True))
    temp_caver = np.ones(canny.shape, np.uint8) * 255
    contours1 = cv2.approxPolyDP(contours[0], 30, True)
    cv2.drawContours(temp_caver, contours1, -1, (0, 255, 0), 1)
    # cv2.imshow("ww" + str(max_index), temp_caver)

    # 备选拐点
    corners = cv2.goodFeaturesToTrack(temp_caver, 25, 0.1, 10)
    if len(contours)==0:
        return 0,False
    # print(corners)
    # criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
    # cv2.cornerSubPix(temp_caver, corners, (11, 11), (-1, -1), criteria)
    # corners = np.int0(corners)
    point_list = []
    for i in corners:
        x, y = i.ravel()
        point_list.append((x, y))

    corner_point = find_corner(point_list)  # 找到4个顶点

    allowed_moving_girth = 300
    global pre_corner_point, count, pre_max_length
    if count == False:
        pre_corner_point = corner_point
        pre_max_length = max_length
        count = True
    sort_corner_list = sort_corner(corner_point)
    # if np.max(abs(np.array(corner_point) - np.array(pre_corner_point))) > allowed_moving_length:
    #     print ("框选错误1")
    #     return 0, 0
    if abs(pre_max_length - max_length) > allowed_moving_girth:
        print ("Frame selection error")
        return 0, False
    # pre_corner_point = corner_point
    # pre_max_length = max_length

    hight, width = calSize(sort_corner_list, scale)
    # img_size = [hight, width]

    aim_size = np.float32([[0, 0], [width, 0], [width, hight], [0, hight]])
    raw_size = []

    for x, y in sort_corner_list:
        raw_size.append([x, y])

    raw_size = np.float32(raw_size)
    translate_map = cv2.getPerspectiveTransform(raw_size, aim_size)
    translate_img = cv2.warpPerspective(source_img, translate_map, (int(width), int(hight)))
    translate_img = cv2.flip(translate_img, 1)  # 对角镜像
    return translate_img,True


def calSize(sort_corner_list, N):
    h1 = (sort_corner_list[2][1] - sort_corner_list[1][1])
    h2 = (sort_corner_list[3][1] - sort_corner_list[0][1])
    hight = max(h1, h2) * N

    w1 = (sort_corner_list[0][0] - sort_corner_list[1][0])
    w2 = (sort_corner_list[3][0] - sort_corner_list[2][0])
    width = max(w1, w2) * N

    return hight, width


def sort_corner(corner_point):
    for i in range(len(corner_point)):
        for j in range(i + 1, len(corner_point)):
            if corner_point[i][1] > corner_point[j][1]:
                tmp = corner_point[j]
                corner_point[j] = corner_point[i]
                corner_point[i] = tmp
    top = corner_point[:2]
    bot = corner_point[2:]

    if top[0][0] > top[1][0]:
        tmp = top[1]
        top[1] = top[0]
        top[0] = tmp

    if bot[0][0] > bot[1][0]:
        tmp = bot[1]
        bot[1] = bot[0]
        bot[0] = tmp

    tl = top[1]
    tr = top[0]
    bl = bot[0]
    br = bot[1]
    # print (tl, tr, bl, br)
    corners = [tl, tr, bl, br]
    return corners


def area(a, b, c):
    return (a[0] - c[0]) * (b[1] - c[1]) - (b[0] - c[0]) * (a[1] - c[1])

def find_corner(point_list):
    corner_num = len(point_list)
    ans = 0.0
    ans_point_index_list = [0, 0, 0, 0]
    m1_point = 0
    m2_point = 0
    for i in range(corner_num):
        for j in range(corner_num):
            if (i == j):
                continue
            m1 = 0.0
            m2 = 0.0

            for k in range(corner_num):
                if (k == i or k == j):
                    continue
                a = point_list[i][1] - point_list[j][1]
                b = point_list[j][0] - point_list[i][0]
                c = point_list[i][0] * point_list[j][1] - point_list[j][0] * point_list[i][1]
                temp = a * point_list[k][0] + b * point_list[k][1] + c

                if (temp > 0):
                    tmp_area = abs(area(point_list[i], point_list[j], point_list[k]) / 2)
                    if tmp_area > m1:
                        m1 = tmp_area
                        m1_point = k

                elif (temp < 0):
                    tmp_area = abs(area(point_list[i], point_list[j], point_list[k]) / 2)
                    if tmp_area > m2:
                        m2 = tmp_area
                        m2_point = k

            if (m1 == 0.0 or m2 == 0.0):
                continue
            if (m1 + m2 > ans):
                ans_point_index_list[0] = i
                ans_point_index_list[1] = j
                ans_point_index_list[2] = m1_point
                ans_point_index_list[3] = m2_point
                ans = m1 + m2
    ans_point_list = []
    for i in ans_point_index_list:
        ans_point_list.append(point_list[i])
    return ans_point_list